package JZOffer;

/**
 * @author Lw中
 * @date 2021/9/5 10:07
 */
public class Jz55II {

    // Jz55 II. 平衡二叉树

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public boolean isBalanced(TreeNode root) {
        // 使用递归计算出左右子树的深度再进行比较
        return res(root) != -1;
    }

    private int res(TreeNode root) {
        if (root == null) return 0;
        int left = res(root.left);
        if (left == -1) return -1;
        int right = res(root.right);
        if (right == -1) return -1;
        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
    }

}
